import { Button, message, Spin, Table } from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import moment from "moment";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import enums from "../creditCar/enums";
import PateoAuthButtons from "@/common/PateoAuthButtons/PateoAuthButtons";
import Ellipsis from "@/components/Ellipsis";
import styles from "./index.less";
import MsgRulerModal from "../warningCar/msgRulerModal";
import MaskText from '@/components/MaskText'
// 下划线转驼峰
function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}

const regExpFields = {
  position_address: 'location',
  lng: 'longitude',
  lat: 'latitude',
  vehicle_owner_name: 'name',
  vehicle_owner_phone: 'phone',
  id_num: 'identity'
}

@connect((state) => ({
  menu: state.menu,
  warningCar: state.warningCar,
  warningRecord:state.warningRecord,
}))
export default class WarningCarDetail extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
  };

  state = {
    vin: "",
    isEdit: false,
    detailData: {},
    statuesData: null,
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
    tboxRouseloading: false,
    tboxRouseCount: 35,
    detailDataNew: [],
    riskOperateShow: false,
    riskWarnShow: false,
    filterItem: ["risk_warn_show", "risk_operate_show"],

    ruleList: [],
    msgRuleModalVisible: false,
    ruleListSelectedRecord: {},
    ruleListType: 1,
    detailInfo: {},
    creditTypeOptions: [],
  };
  handlemsgRemove = (record) => {
    const { dispatch } = this.props;
    let params = {
      businessCode: "warn-vehicle-log",
      vin: record.vin,
    };

    dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/ivi/warn/remove",
        ...params,
      },
      callback: (response) => {
        if (response.statusCode === "0") {
          message.success("修改成功");
          this.handleGetVehicleDetail(record.vin);
          this.handleTableData();
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };
  handleWarnMsg = (record) => {
    let params = {
      businessCode: "warn-vehicle-log",
      vin: record.vin,
      iviNoticeId: "",
    };
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/ivi/warn",
        ...params,
      },
      callback: (response) => {
        if (response.statusCode === "0") {
          message.success("发送成功");

          this.handleGetVehicleDetail(record.vin);
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handlemsgRulerList = (record, type) => {
    // 0-正常行驶，1-锁车，2-跛行
    let showTypes = [2, 3];
    if (record.riskStatus == "正常行驶") {
      showTypes = [1, 2, 3];
    }
    this.props.dispatch({
      type: "thirdOrgCreditVehicleRiskImpleRule/noticeList",
      payload: showTypes,
      callback: (response) => {
        if (response && response.statusCode == "0") {
          this.setState({
            ruleList: response.data,
            msgRuleModalVisible: true,
            ruleListSelectedRecord: record,
            ruleListType: type,
          });
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };
  addPreinstall = (columns) => {
    return columns.map((i) => {
      const sameTitle = columns.some(
        (j) => j.name === i.name && i.fieldId !== j.fieldId
      );
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`;
      }
      return i;
    });
  };
  componentDidMount() {
    let vin = sessionStorage.getItem("vin");
    this.setState({ vin });
    const typeOption = sessionStorage.getItem("typeOption");
    this.setState({ creditTypeOptions: JSON.parse(typeOption)});
    this.props.dispatch({
      // 更多筛选数据
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=warning&scene=detail",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            if (response.data.some((i) => i.column == "risk_operate_show")) {
              this.setState({ riskOperateShow: true });
              this.queryRecordList();//风控操作记录列表
            }
            if (response.data.some((i) => i.column == "risk_warn_show")) {
              this.setState({ riskWarnShow: true });
              this.handleTableData();//预警信息列表--风控预警记录分页查询
            }
            // 脱敏字段添加正则校验类型
            let enhanceData = response.data.map(item => {
              if(regExpFields[item.column]) {
                return {
                  ...item,
                  regExpType: regExpFields[item.column]
                }
              }
              return item;
            })
            console.log('enhanceData',enhanceData)
            this.setState({
              fieldDetail: this.addPreinstall(
                enhanceData.filter(
                  (i) => !this.state.filterItem.some((j) => i.column == j)
                )
              ),
            });
            this.handleGetVehicleDetail(vin);
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  }
  queryRecordList = () => {//风控操作记录列表
    const { dispatch } = this.props;
    const { vin } = this.state;

    dispatch({
      type: "warningRecord/riskResultList",
      payload: {
      url: '/mscreditbusiness/vehicle/risk/warn/result/page',
      businessCode: "warn-vehicle-log",
        curPage: 1,
        pageSize: 10,
        vin,
      },
    });
  };
  handleTableData = () => {//预警信息列表
    const { curPage, pageSize } = this.state;
    const vin = sessionStorage.getItem("vin");
    const detailInfo = JSON.parse(sessionStorage.getItem("detailInfo") || "{}");
    console.log("detailInfo", detailInfo);
    this.setState({
      detailInfo: detailInfo,
    });

    this.setState({
      tableLoading: true,
    });

    let submitData = { vin, curPage, pageSize };

    this.props.dispatch({
      type: "warningCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/risk/warn/record/page",
        ...submitData,
      },
      callback: (response) => {
        if (response && response.statusCode == "0" && response.data) {
          if (
            response.data.rows.length === 0 &&
            response.data.pagination.current > 1
          ) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              }
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== "0") {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleGetVehicleDetail2 = (vin) => {//获取预警车详情
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/warn/detail",
        vin: vin,
        businessCode: "warning",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data.overdueDate) {
            response.data.overdueDate = moment(
              response.data.overdueDate
            ).format("YYYY-MM-DD");
          }
          if (response.data.financeBeginDate) {
            response.data.financeBeginDate = moment(
              response.data.financeBeginDate
            ).format("YYYY-MM-DD");
          }
          if (response.data.positionDate) {
            response.data.positionDate = moment(
              response.data.positionDate
            ).format("YYYY-MM-DD HH:mm:ss");
          }
          if (response.data.lastUpDate) {
            response.data.lastUpDate = moment(response.data.lastUpDate).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
          if (response.data) {
            let findText = enums.riskWarnStatus.array.find(
              (e) => e.value == response.data.riskWarnStatus
            );
            if (findText) {
              response.data.riskWarnStatus = findText.label;
            }
            let findText2 = enums.repaymentStatus.array.find(
              (e) => e.value == response.data.repaymentStatus
            );
            if (findText2) {
              response.data.repaymentStatus = findText2.label;
            }
          }

          // this.handleGetVehicleStatues(vin);
          this.handleTableData();
          this.setState({
            detailData: response.data,
          });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  // handleGetVehicleStatues = (vin) => {
  //   this.props.dispatch({
  //     type: "http2/getDataWithRes",
  //     payload: {
  //       url: "/third/credit/vehiclestatus",
  //       vin: vin,
  //     },
  //     callback: (response) => {
  //       if (response && response.statusCode == "0" && response.data.status) {
  //         this.setState({
  //           statuesData: response.data.status,
  //         });
  //       } else {
  //         if (response.statusCode != "0") {
  //           message.error(response.statusMessage);
  //         }
  //       }
  //     },
  //   });
  // };

  handleLocation = (vin) => {
    sessionStorage.setItem("vin", vin);
    sessionStorage.setItem("businessCode", "warn-vehicle-log");
    sessionStorage.setItem(
      "warningCarLocationbackPath",
      "/creditPlatform/overdueCarDetail"
    );
    this.props.dispatch(
      routerRedux.push({
        pathname:
          "/creditPlatform/warningCarLocation",
      })
    );
  };

  handleLockCar = (vin) => {
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/lock/set",
        vin: vin,
        businessCode: "warn-vehicle-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("操作成功");
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleUnlockCar = (vin) => {
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/lock/remove",
        vin: vin,
        businessCode: "warn-vehicle-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("操作成功");
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleLimp = (vin) => {
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/limp/set",
        vin: vin,
        businessCode: "warn-vehicle-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("操作成功");
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleUnlimp = (vin) => {
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/limp/remove",
        vin: vin,
        businessCode: "warn-vehicle-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("操作成功");
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  //点击TBOX唤醒
  handleTboxRouse = (vin) => {
    this.setState({
      tboxRouseloading: true,
    });
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/tbox/wake",
        vin: vin,
        businessCode: "warn-vehicle-log",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("已经给该车辆发送远程唤醒指令");
          let tboxRouseCount = 35;
          let tboxRouseSearchCount = 3;
          this.timer = setInterval(() => {
            tboxRouseCount--;
            this.setState({ tboxRouseCount });
            //请求详情接口
            if (tboxRouseCount <= 0) {
              this.setState({
                tboxRouseloading: false,
                tboxRouseCount: 35,
              });
              clearInterval(this.timer);
              message.error("TBOX没有被成功唤醒");
            }
          }, 1000);

          this.timer2 = setInterval(() => {
            tboxRouseSearchCount--;
            //请求详情接口
            this.props.dispatch({
              type: "warningCar/postDataWithRes",
              payload: {
                url: "/mscreditbusiness/vehicle/tbox/wake/result",
                vin: vin,
              },
              callback: (response) => {
                if (response && response.statusCode == "0") {
                  //比较TBOX失联天数
                  // if (!response.data.tboxLostDays) {
                  if (response.data) {
                    message.success("TBOX被成功唤醒");
                    this.handleTableData();
                    this.handleGetVehicleDetail(vin);
                    clearInterval(this.timer2);
                    clearInterval(this.timer);
                    this.setState({
                      tboxRouseloading: false,
                      tboxRouseCount: 35,
                    });
                  }
                } else {
                  message.error(response.statusMessage);
                }
              },
            });

            if (tboxRouseSearchCount <= 0 || tboxRouseCount <= 0) {
              clearInterval(this.timer2);
            }
          }, 10000);
        } else {
          message.error(response.statusMessage);
          this.setState({
            tboxRouseloading: false,
            tboxRouseCount: 35,
          });
        }
      },
    });
  };
  handleGetVehicleDetail = (vin) => {//详情
    this.props.dispatch({
      type: "warningCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/vehicle/warn/detail",
        vin: vin,
        businessCode: "warning",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          const specialData = this.specialDataGenrator();
          if (response.data.overdueDate) {
            response.data.overdueDate = moment(response.data.overdueDate);
          }
          if (response.data.financeBeginDate) {
            response.data.financeBeginDate = moment(
              response.data.financeBeginDate
            ).format("YYYY-MM-DD");
          }
          if (response.data.positionDate) {
            response.data.positionDate = moment(
              response.data.positionDate
            ).format("YYYY-MM-DD HH:mm:ss");
          }
          let detailData = response.data;
          if (response.data.fenceInfo && response.data.fenceInfo.length >0) {
            let regExpKeys = Object.keys(regExpFields).map(key => toCamel(key))
            const list = response.data.fenceInfo;
          const keylist = list[0];
          const obj = {}
          for(let key in keylist){
             list.map(item =>{
                if(!obj[key]){
                  obj[key]=[];
                }
                if(item[key]){
                 obj[key].push(item[key])
                }else{
                  obj[key].push('暂无信息')
                }
             })
           }
           for(let key in obj){
            if(obj[key] && obj[key].length >0){
              const newValue = obj[key].join('/')
                if(regExpKeys.includes(key)) {
                  obj[key]= newValue
                } else {
                  obj[key]=<Ellipsis length={18} tooltip>{newValue}</Ellipsis>;
                }  
            }
           }
           detailData =  Object.assign(response.data, obj);
          }
          const newDatas = this.createDetail(
            detailData,
            this.state.fieldDetail,
            specialData
          );
          console.log(newDatas);

          this.setState({
            detailDataNew: newDatas,
            isEdit: false,
            detailData: response.data,
          });
          // this.handleGetVehicleStatues(vin);
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  createDetail = (detailData, fieldDetail, specialData) => {
    // console.log(specialData);
    if (detailData.warnType == 2 && detailData.warnStatus == 1) {
      fieldDetail.push({
        column: "last_ack_date",
        createDate: detailData.lastAckDate,
        extra: null,
        groupName: "车辆风控信息",
        name: "车机告警最新回执时间",
        type: 6,
      });
    }
    const _cc = fieldDetail.reduce((total, currentValue) => {
      const info = detailData[toCamel(currentValue.column)];
      const speInfo = specialData.find((i) => i.column == currentValue.column);
      const item = { ...currentValue, ...speInfo, info };
      let flag = true;
      total = total.map((i) => {
        if (i.groupName == currentValue.groupName) {
          flag = false;
          i.list.push(item);
        }
        return i;
      });
      if (flag) {
        total.push({
          groupName: currentValue.groupName,
          list: [item],
        });
      }
      return total;
    }, []);
    return _cc;
  };
  specialDataGenrator = () => {
    // 生成特殊字段
    return [
      {
        column: "limp_enable",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "不支持",
            },
            {
              value: "1",
              label: "支持",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        // 实车当前状态
        column: "vhl_current_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "锁车",
            },
            {
              value: 2,
              label: "跛行",
            },
            {
              value: 3,
              label: "待车辆反馈",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        column: "warn_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "暂不支持",
            },
            {
              value: 1,
              label: "不可配置",
            },
            {
              value: 2,
              label: "可配置",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "车机告警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "repayment_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 0-还款中；1-已逾期；2-已结清；3-融资已到期
              value: "0",
              label: "还款中",
            },
            {
              value: "1",
              label: "已逾期",
            },
            {
              value: "99",
              label: "未知",
            },
            {
              value: "2",
              label: "已结清",
              hideInOption: true,
            },
            {
              value: "3",
              label: "融资已到期",
            },
          ],
        },
        nullValue: "未知",
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 1：预警  0或null：未预警 ；
              value: "0",
              label: "未预警",
            },
            {
              value: "1",
              label: "预警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "engine_state",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //  2-点火；0-熄火
              value: "0",
              label: "熄火",
            },
            {
              value: "2",
              label: "点火",
            },
            {
              value: "",
              label: "行驶中",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "risk_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //   0-正常行驶，1-锁车，2-跛行
              value: "0",
              label: "正常行驶",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        column: "credit_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.creditTypeOptions,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
    ];
  };
  componentWillUnmount() {
    clearInterval(this.timer2);
    clearInterval(this.timer);
  }

  handleOnReturn = () => {
    const backPath = sessionStorage.getItem("backPath");
    this.props.dispatch(
      routerRedux.push({
        pathname: backPath,
      })
    );
  };
  handleTableChangeA = (page) => {
    const { dispatch } = this.props;
    const { vin } = this.state;
    const params = {
      businessCode: "warn-vehicle-log",
      curPage: page.current,
      pageSize: page.pageSize,
      vin,
    };
    dispatch({
      type: "warningRecord/riskResultList",
          payload: {
          url: '/mscreditbusiness/vehicle/risk/warn/result/page',
          ...params
      },
    });
  };
  render() {
    const {
      detailData,
      statuesData,
      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
      tboxRouseloading,
      tboxRouseCount,
    } = this.state;
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    const locationBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_location');
    const lockCarBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_lockCar');
    const unlockCarBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_unlockCar');
    const limpBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_limp');
    const unlimpBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_unlimp');
    const tboxRouseBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_tboxRouse');
    const columnsA = [
      {
        title: "序号",
        dataIndex: "num",
        width: "7%",
        render: (text, record, index) => {
          return pagination.pageSize * (pagination.current - 1) + index + 1;
        },
      },
      {
        title: "执行时间",
        dataIndex: "operateTime",
        render: (text, record) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
      },
      { 
        title: "执行人",
        dataIndex: "operator",
        render(val) {
          return <MaskText text={val} type="name" />;
        }
      },
      { title: "风控实施记录", dataIndex: "operationContent" },
    ];
    const columnsB = [
      {
        title: "预警时间",
        dataIndex: "riskTriggerDate",
        render: (text) => {
          if (text) {
            return moment(text).format("YYYY-MM-DD HH:mm:ss");
          }
        },
      },
      {
        title: "预警内容",
        dataIndex: "riskWarnMsg",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "触发的异常事件",
        dataIndex: "riskEventContent",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "已实施的管控措施",
        dataIndex: "riskControlResult",
        render: (text) => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: "处理状态",
        dataIndex: "dealStatus",
        render: (text, record) => {
          let findText = enums.dealStatus.array.find((e) => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: "操作",
        dataIndex: "opt",
        fixed: "right",
        align: "center",
        render: (text, record) => {
          if (record.dealStatus == enums.dealStatus.deal.value) {
            return;
          }
          const { detailData } = this.state;
          const { warnType, warnStatus } = this.state.detailData;
          // console.log(warnType, warnStatus, detailData);
          const warnBtnAuth = permissions.includes(pathname + '/' + 'warningCarDetail_warn');
          const isWarn =
            warnBtnAuth &&
            warnType != 0 &&
            ((warnType == 1 && this.state.detailInfo.overdueDays >= 1) ||
              warnType == 2);
          const btns = [];

          const locationBtn = {
            title: "查看定位",
            key: "location",
            onConfirm: () => this.handleLocation(record.vin),
          };

          let lockMsg =
            detailData.riskStatus == enums.riskStatus.limp.value
              ? "该车已处于跛行状态，是否解除跛行状态并实施锁车?"
              : "确认锁车吗?";

          let lockMsgAndWarn =
            detailData.riskStatus === "跛行"
              ? "该车已处于跛行状态，是否解除跛行状态并实施锁车和车机告警吗?"
              : "确认锁车和车机告警吗?";

          const lockCarBtn = {
            title: "锁车",
            Popconfirm: true,
            message: isWarn && warnType == 1 ? lockMsgAndWarn : lockMsg,
            key: "lockCarBtn",
            onConfirm: () =>
              isWarn && warnType != 1
                ? this.handlemsgRulerList(record, 2)
                : this.handleLockCar(record.vin),
          };

          const unlockCarBtn = {
            title: "解除锁车",
            Popconfirm: true,
            message: "确认解锁车辆吗?",
            key: "unlockCarBtn",
            onConfirm: () => this.handleUnlockCar(record.vin),
          };

          let limpMsg =
            detailData.riskStatus == enums.riskStatus.lock.value
              ? "该车已处于锁车状态，是否解除锁车状态并实施跛行?"
              : "确认设置跛行吗?";

          let limpMsgAndWarn =
            detailData.riskStatus === "锁车"
              ? "该车已处于锁车状态，是否解除锁车状态并实施跛行和车机告警吗？"
              : "确认设置跛行和车机告警吗?";

          const limpBtn = {
            title: "跛行",
            Popconfirm: true,
            message: isWarn && warnType == 1 ? limpMsgAndWarn : limpMsg,
            key: "limp",
            onConfirm: () =>
              isWarn && warnType != 1
                ? this.handlemsgRulerList(record, 3)
                : this.handleLimp(record.vin),
          };

          const unlimpbtn = {
            title: "解除跛行",
            Popconfirm: true,
            message: "确认解除跛行吗?",
            key: "unlimp",
            onConfirm: () => this.handleUnlimp(record.vin),
          };

          const tboxRouseBtn = {
            title: "TBOX唤醒",
            Popconfirm: true,
            message: "是否要对TBOX进行远程唤醒?",
            key: "tboxRouse",
            onConfirm: () => this.handleTboxRouse(record.vin),
          };

          if (record.riskStatus == enums.riskStatus.driving.value) {
            if (locationBtnAuth) btns.push(locationBtn);
            //判断车辆是否支持跛行
            if (record.limpEnable == enums.limpEnable.support.value) {
              if (limpBtnAuth) btns.push(limpBtn);
            }
            if (lockCarBtnAuth) btns.push(lockCarBtn);
          }

          if (record.riskStatus == enums.riskStatus.lock.value) {
            if (unlockCarBtnAuth) btns.push(unlockCarBtn);
            if (locationBtnAuth) btns.push(locationBtn);
            //判断车辆是否支持跛行
            if (record.limpEnable == enums.limpEnable.support.value) {
              if (limpBtnAuth) btns.push(limpBtn);
            }
          }

          if (record.riskStatus == enums.riskStatus.limp.value) {
            //判断车辆是否支持跛行
            if (record.limpEnable == enums.limpEnable.support.value) {
              if (unlimpBtnAuth) btns.push(unlimpbtn);
            }
            if (locationBtnAuth) btns.push(locationBtn);
            if (lockCarBtnAuth) btns.push(lockCarBtn);
          }

          if (record.tboxLostDays && record.tboxLostDays >= 1) {
            if (tboxRouseBtnAuth) btns.push(tboxRouseBtn);
          }

          const msgRulerBtn = {
            title: "车机告警",
            Popconfirm: true,
            message: "是否车机告警",
            key: "msgrulerBtn",
            onConfirm: () =>
              warnType == 1
                ? this.handleWarnMsg(record)
                : this.handlemsgRulerList(record, 1),
          };
          const releaseRulertn = {
            title: "解除车机告警",
            Popconfirm: true,
            message: "是否解除车机告警",
            key: "msgremoverulerBtn",
            onConfirm: () => this.handlemsgRemove(record),
          };
          if (isWarn) {
            if (warnStatus == 1) {
              btns.push(releaseRulertn);
            } else {
              btns.push(msgRulerBtn);
            }
          }

          return (
            <PateoAuthButtons
              authStr="thirdOrgCreditVehicleWarningCar"
              btns={btns}
            />
          );
        },
      },
    ];

    const paginationB = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };
    const {
      warningRecord: {
        // detailLoading,
        riskResultList,
        pagination,
      },
    } = this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>
          共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条
        </span>
      ),
    };
    const wrningTableProps = {
      columns: columnsB,
      pagination: paginationB,
      rowKey: "sid",
      scroll: { x: "max-content" },
      // loading: tableLoading,
      dataSource: this.state.tableData,
      onChange: (pagination) => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          }
        );
      },
    };

    return (
      <Spin
        spinning={tboxRouseloading}
        size="large"
        tip={`Loading(${tboxRouseCount})s`}
      >
        <div className={styles.root}>
          <div className={styles.topBtn}>
            <Button type="primary" onClick={() => this.handleOnReturn()}>
              返回
            </Button>
          </div>
          <div className={styles.midContent}>
            {this.state.detailDataNew.map((i) => (
              <div
                key={`groupName${i.groupName}`}
                className={styles.publicItem}
              >
                <div className={styles.itemTitle}>{i.groupName}</div>
                <div className={styles.itemContent}>
                  {i.list.map((j) => (
                    <div
                      key={`list${j.column}`}
                      className={styles.itemContentRow}
                    >
                      <div className={styles.rowTitle}>{j.name}:</div>
                      {/* <div className={styles.rowValue}>{j.type == 2}</div> */}
                      <div className={styles.rowValue}>
                        {j.type == 4 &&
                          j.info &&
                          (typeof j.info == "number"
                            ? moment(j.info).format("YYYY-MM-DD")
                            : moment(j.info, "YYYY-MM-DD").format(
                                "YYYY-MM-DD"
                              ))}
                        {j.type == 5 &&
                          j.info &&
                          (typeof j.info == "number"
                            ? moment(j.info).format("HH:mm:ss")
                            : moment(j.info, "HH:mm:ss").format("HH:mm:ss"))}
                        {j.type == 6 &&
                          j.info &&
                          (typeof j.info == "number"
                            ? moment(j.info).format("YYYY-MM-DD HH:mm:ss")
                            : moment(j.info, "YYYY-MM-DD HH:mm:ss").format(
                                "YYYY-MM-DD HH:mm:ss"
                              ))}
                        {j.type == 2 &&
                          j.extra &&
                          (j.info !== null
                            ? typeof j.extra == "string"
                              ? j.info !== null
                              : j.extra.optionList?.find(
                                  (n) => n.value == j.info
                                )
                              ? j.extra.optionList?.find(
                                  (n) => n.value == j.info
                                ).label
                              : j.info
                            : j.nullValue || "")}
                        {j.type == 7 && j.info && (
                          <a href={`${j.info}`} target="_blank">
                            {j.info}
                          </a>
                        )}
                        {j.type != 2 &&
                          j.type != 4 &&
                          j.type != 5 &&
                          j.type != 6 &&
                          j.type != 7 &&
                          (j.regExpType ? <MaskText text={j.info} type={j.regExpType} />: (j.info || j.info === 0 ? j.info : ""))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>

          {this.state.riskOperateShow && (
            <div className={styles.midContent} style={{ paddingTop: "20px" }}>
              <div className={styles.publicItem}>
                <div className={styles.itemTitle}>风控操作记录列表</div>
                <div className={styles.itemContent}>
                  <div
                    className={styles.itemContentRow}
                    style={{ width: "100%" }}
                  >
                    <Table
                      style={{ width: "100%" }}
                      // loading={detailLoading}
                      columns={columnsA}
                      dataSource={riskResultList}
                      pagination={paginationProps}
                      onChange={this.handleTableChangeA}
                    />
                  </div>
                </div>
              </div>
            </div>
          )}

          {this.state.riskWarnShow && (
            <div className={styles.midContent} style={{ paddingTop: "20px" }}>
              <div className={styles.publicItem}>
                <div className={styles.itemTitle}>预警信息列表</div>
                <div className={styles.itemContent}>
                  <div
                    className={styles.itemContentRow}
                    style={{ width: "100%" }}
                  >
                    <Table style={{ width: "100%" }} {...wrningTableProps} />
                  </div>
                </div>
              </div>
            </div>
          )}

          {this.state.msgRuleModalVisible && (
            <MsgRulerModal
              changeVisible={() => {
                this.setState({ msgRuleModalVisible: false });
                // this.handleGetVehicleDetail(this.state.vin);
                // this.handleTableData();
              }}
              onOk={() => {
                this.setState({ msgRuleModalVisible: false });
                this.handleGetVehicleDetail(this.state.vin);
                this.handleTableData();
              }}
              businessCode="warn-vehicle-log"
              visible={this.state.msgRuleModalVisible}
              ruleList={this.state.ruleList}
              record={this.state.ruleListSelectedRecord}
              dispatch={this.props.dispatch}
              ruleListType={this.state.ruleListType}
            />
          )}
        </div>
      </Spin>
    );
  }
}
